package org.scep.utils;

import java.io.UnsupportedEncodingException;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

public class Utils
{
	public static boolean isEmpty(String str){
		if(str == null)
			return true;
		if(str.trim().equals(""))
			return true;
		
		return false;
	}
	
	public static byte[] toBinArray(String hexStr){
		int ch,ch2,ch3;
		byte[] b = new byte[hexStr.length()/2];
		for(int i=0,len=hexStr.length();i<len;i+=2){
			ch = hexStr.charAt(i);
			if (Character.isLetter(ch) || Character.isDigit(ch)) {
				ch2 = hexStr.charAt(i+1);
				ch3 = Integer.parseInt((char) ch + "" + (char) ch2, 16);
				b[i/2]=(byte)ch3;
			}
		}
		return b;
	}
	
	public static String toHexString(byte[] b,int len){
		String str="";
		int ch;
		for(int i=0;i<len;i++){
			ch = b[i];
			String hexValue = Integer.toHexString(ch);
			if (hexValue.length() == 1){
				hexValue = "0" + hexValue;
			}
			str += hexValue;
		}
		return str;
	}
	
	public static String URLDecode(String s){
		try{
			return java.net.URLDecoder.decode(s.replaceAll("%20","+"),"UTF-8");
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
			return s;
		}
	}
	
	public static String toUTF8String(String text){
		
		if(isEmpty(text))
			return "";
		
		return text;
		
//		try{
//			return new String(text.getBytes("8859_1"), "UTF-8");
//		}
//		catch (UnsupportedEncodingException e)
//		{
//			e.printStackTrace();
//			return "";
//		}
	}
	
	public static String getRequestContentToString(HttpServletRequest request) {
		StringBuffer sbs = new StringBuffer();
		try{
			int contentLength = request.getContentLength();
			ServletInputStream sis = request.getInputStream();
			byte[] b = new byte[1024];
			int l = 0, k = 0;
			while(k<contentLength&&(l=sis.read(b, 0, 1024))!=-1){
				sbs.append(new String(b,0,l,"UTF-8"));
				k+=l;
			}
		}catch(Exception ex){}
		return sbs.toString();
	}
	
	public static byte[] getRequestContentToBytes(HttpServletRequest request) {
		byte[] sbs = null;
		try{
			int contentLength = request.getContentLength();
			sbs = new byte[contentLength];
			ServletInputStream sis = request.getInputStream();
			int l = 0, k = 0;
			while(k<contentLength&&(l=sis.read(sbs, k, contentLength-k))!=-1){
				k+=l;
			}
		}catch(Exception ex){}
		return sbs;
	}
}
